import {
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PieChartOutlined,
  UserOutlined
} from '@ant-design/icons';
import { Layout, Menu, Avatar, Dropdown,  Space, message } from 'antd'
import type { MenuProps } from 'antd';
import React, { useEffect, useState } from 'react'
import { Outlet, useNavigate, useLocation, Navigate } from 'react-router-dom'
// import type { MenuProps } from 'antd';
import axios from '../../utils/request'
import PubSub from 'pubsub-js'
import './index.css'

const { Header, Sider, Content } = Layout

// type MenuItem = Required<MenuProps>['items'][number];

// function getItem(
//   label: React.ReactNode,
//   key: React.Key,
//   icon?: React.ReactNode,
//   children?: MenuItem[],
//   type?: 'group',
// ): MenuItem {
//   return {
//     key,
//     icon,
//     children,
//     label,
//     type,
//   } as MenuItem;
// }

// const items: MenuItem[] = [
//   getItem('首页', '/home', <PieChartOutlined />),
//   getItem('用户管理', '/user-manager', <DesktopOutlined />, [
//     getItem('用户列表', '/user-manager/list')
//   ]),
//   getItem('权限管理', '/right-manage', <ContainerOutlined />, [
//     getItem('角色列表', '/right-manage/role/list'), 
//     getItem('权限列表', '/right-manage/right/list')
//   ]),

//   getItem('新闻管理', '/news-manage', <MailOutlined />, [
//     getItem('撰写新闻', '/news-manage/add'),
//     getItem('草稿箱', '/news-manage/draft'),
//     getItem('新闻分类', '/news-manage/category'),
//   ]),

//   getItem('审核管理', '/audit-manage', <AppstoreOutlined />, [
//     getItem('审核新闻', '/audit-manage/audit'),
//     getItem('审核列表', '/audit-manage/list')
//   ]),
//   getItem('发布管理', '/publish-manage', <AppstoreOutlined />, [
//     getItem('待发布', '/publish-manage/unpublished'),
//     getItem('已发布', '/publish-manage/published'),
//     getItem('已下线', '/publish-manage/sunset'),
//   ]),
// ];
interface DataType {
  key: string
  label: string
  id: number
  grade: number
  children?: DataType[]
  pagepermisson?: number
  rightId?: number
}
const NewsSandBox: React.FC = () => {
  const onClick: MenuProps['onClick'] = ({ key }) => {
    if(key === '2'){
      localStorage.removeItem('token')
      navigate('/login')
    }
  };
  const menu = (
    <Menu
      onClick={onClick}
      items={[
        {
          key: '1',
          label: (<span>超级管理员</span>),
        },
        {
          key: '2',
          danger: true,
          label: (<span>退出登录</span>),
        }
      ]}
    />
  );
  function getData() {
    axios.get('/rights?_embed=children')
    .then(({data}) => {
      data.forEach((item: DataType) => {
        if(item.children?.length !== 0){
          item.children?.forEach(item => delete item.rightId)
          item.children = item.children?.filter(item => item.pagepermisson === 1)
        }else delete item.children
      })
      data = data.filter((item: DataType) => item.pagepermisson === 1)
      data = data.filter((item: DataType) => currentUser.role.rights.includes(item.key))
      setrightList(data)
    })
  }
  useEffect(() =>{
    getData()
    const pubId = PubSub.subscribe('updData',() => getData())
    return () => {
      PubSub.unsubscribe(pubId)
    }
  }, [])
  const [collapsed, setCollapsed] = useState(false)
  const [rightList, setrightList] = useState<DataType[]>([])
  const navigate = useNavigate()
  const location = useLocation()

  const currentUser = JSON.parse((localStorage.getItem('token') as string))
  return (
    <Layout>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <h1 style={{color: 'white',textAlign: 'center'}}>新闻发布管理系统</h1>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={[location.pathname]}
          defaultOpenKeys={['/' + location.pathname.split('/')[1]]}
          items={rightList}
          onSelect={({ key }) => navigate(key)}
        />
      </Sider>
      <Layout className="site-layout">
        <Header className="site-layout-background" style={{ paddingLeft: '24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: 'trigger',
            onClick: () => setCollapsed(!collapsed),
          })}
          <div className="right">
            <span style={{marginRight: '20px'}}>欢迎{currentUser.username}回来</span>
            <Dropdown overlay={menu}>
              <a onClick={(e) => e.preventDefault()}>
                <Space>
                <Avatar icon={<UserOutlined />} />
                </Space>
              </a>
            </Dropdown>
          </div>
        </Header>
        <Content
          className="site-layout-background"
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            overflow: 'auto'
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  )
}

export default NewsSandBox
